import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
import 'package:universal_html/html.dart' as html;

import '../../../network/Api.dart';
import '../../../utils/page.dart';
import '../../../utils/provider.dart';
import '../../../utils/snack_bar.dart';
import '../../../widget/date_picker/flutter_datetime_picker.dart';


class ProfileCompleteV2Ui extends StatefulWidget {
  final String smsSig;

  const ProfileCompleteV2Ui(this.smsSig, {Key? key}) : super(key: key);

  @override
  State<ProfileCompleteV2Ui> createState() => _ProfileCompleteWidget();
}

class _ProfileCompleteWidget extends State<ProfileCompleteV2Ui> {
  late Size _screen;
  final _nickNameController = TextEditingController();
  int _gender = 2;
  final _birthdayController = TextEditingController();
  final _addressController = TextEditingController();
  final _pcaOriginalList = [];
  final _pcaList = [];
  String? _albumId = "";

  late String _avatarFilePath = "";

  @override
  void initState() {
    super.initState();
    _getPcaList();
  }

  _getPcaList() async {
    final Response<dynamic> res = await Api.getInstance().getPcaList();
    _pcaOriginalList.addAll(res.data);
    for (var i in res.data) {
      final item = <String, dynamic>{};
      final cities = [];
      for (var c in i['children']) {
        final area = [];
        final city = <String, dynamic>{};
        for (var a in c['children']) {
          area.add(a['name']);
        }
        city[c['name']] = area;
        cities.add(city);
      }
      item[i['name']] = cities;
      _pcaList.add(item);
    }
  }

  @override
  Widget build(BuildContext context) {
    _screen = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: () {
        Navigator.of(context).pop(null);
      },
      child: Container(
        decoration: ShapeDecoration(
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
            color: Colors.white),
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Align(
                alignment: Alignment.topCenter,
                child: Text(
                  "完善资料",
                  style: TextStyle(fontSize: 16, color: ThemeColor.textColor),
                ),
              ),

              Container(
                margin: const EdgeInsets.only(top: 40.0),
                child: Stack(children: [
                  GestureDetector(
                    child: _avatarFilePath.isNotEmpty
                        ? ClipRRect(
                            borderRadius: BorderRadius.circular(5),
                            // borderRadius: BorderRadius.circular(5),

                            child: Image(
                              image: CachedNetworkImageProvider(
                                  Provider.fixAvatar(_avatarFilePath)),
                              height: 86,
                              width: 86,
                            ),
                          )
                        : Image.asset(
                            'images/ic_AvtarMe.png',
                            width: 86,
                            height: 86,
                          ),
                    onTap: () {
                      getAlbumImg();
                    },
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 65, left: 65),
                    child: Image.asset(
                      "images/my_xj.png",
                      width: 28,
                      height: 28,
                    ),
                  ),
                ]),
              ),
              // const SizedBox(height: 24,),
              // const Divider(color: Color(0xFFD8D8D8), height: 1,),
              // const SizedBox(height: 12,),
              //昵称
              Container(
                alignment: Alignment.topLeft,
                margin: const EdgeInsets.fromLTRB(41, 51, 0, 0),
                child: Text(
                  "昵称",
                  style: TextStyle(fontSize: 16, color: ThemeColor.textColor),
                ),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(41, 10, 41, 0),
                height: 45,
                color:const Color(0xFFF6F8FA),
                child: TextField(
                  controller: _nickNameController,
                  maxLength: 11,
                  keyboardType: TextInputType.phone,
                  cursorColor: const Color(0xFFFB6D99),
                  style:
                      const TextStyle(fontSize: 12, color: Color(0xFF222222)),
                  decoration: InputDecoration(
                    hintText: "请输入昵称",
                    counterText: "",
                    border: InputBorder.none,
                    hintStyle: const TextStyle(color: Color(0xFF999999)),
                    fillColor: const Color(0xffF1F3FB),
                    filled: true,
                    enabledBorder: const OutlineInputBorder(
                      /*边角*/
                      borderRadius: BorderRadius.all(
                        Radius.circular(5), //边角为30
                      ),
                      borderSide: BorderSide(
                        color: Colors.white54, //边线颜色为黄色
                        width: 1, //边线宽度为2
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Colors.white54, //边框颜色为绿色
                        width: 1, //宽度为5
                      ),
                    ),
                  ),
                  onChanged: (e) {
                    setState(() {
                    });
                  },
                ),
              ),

              //性别
              const SizedBox(
                height: 10,
              ),
              Container(
                margin: const EdgeInsets.only(left: 41),
                alignment: Alignment.topLeft,
                child: const Text(
                  "性别",
                  style: TextStyle(fontSize: 16),
                ),
              ),

              const SizedBox(
                height: 8,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const SizedBox(
                    width: 41,
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _gender = 2;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 44,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            border: _gender == 2
                                ? Border.all(
                                    color: const Color(0xFFFF5998),
                                    width: 2,
                                  )
                                : null,
                            color:
                                Color(_gender == 2 ? 0xFFF5D8E3 : 0xFFC8CACB)),
                        child: IconText(
                          "    女士",
                          icon: Image.asset(
                            "images/ic_avatar_def_girl.png",
                            width: 32,
                            height: 32,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 41,
                  ),
                  Expanded(
                    flex: 1,
                    child: GestureDetector(
                      onTap: () {
                        setState(() {
                          _gender = 1;
                        });
                      },
                      child: Container(
                        alignment: Alignment.center,
                        width: (_screen.width - 42) / 2,
                        height: 44,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(8),
                            border: _gender == 1
                                ? Border.all(
                                    color: const Color(0xFF59B8FF),
                                    width: 2,
                                  )
                                : null,
                            color:
                                Color(_gender == 1 ? 0xFFD8EAF5 : 0xFFC8CACB)),
                        child: IconText(
                          "    男士",
                          icon: Image.asset(
                            "images/ic_avatar_def_boy.png",
                            width: 32,
                            height: 32,
                          ),
                        ),
                      ),
                    ),
                  ),
                  const SizedBox(
                    width: 41,
                  ),
                ],
              ),

              Container(
                alignment: Alignment.topLeft,
                margin: const EdgeInsets.fromLTRB(41, 10, 0, 0),
                child: const Text(
                  "性别提交后无法更改哦",
                  style: TextStyle(fontSize: 12, color: Color(0xFF7F69D9)),
                ),
              ),
              const SizedBox(
                height: 14,
              ),

              //生日
              Container(
                alignment: Alignment.topLeft,
                margin: const EdgeInsets.only(left: 41),
                child: Text(
                  "生日",
                  style: TextStyle(fontSize: 16, color: ThemeColor.textColor),
                ),
              ),
              Container(
                margin: const EdgeInsets.fromLTRB(41, 10, 41, 0),
                height: 45,
                color: const Color(0xFFF6F8FA),
                child: TextField(
                  controller: _birthdayController,
                  maxLength: 11,
                  keyboardType: TextInputType.phone,
                  cursorColor: const Color(0xFFFB6D99),
                  style:
                      const TextStyle(fontSize: 12, color: Color(0xFF222222)),
                  readOnly: true,
                  decoration: InputDecoration(
                    hintText: "请选择",
                    hintStyle: TextStyle(
                        fontSize: 12, color: ThemeColor.textColorSecond),
                    counterText: "",
                    border: InputBorder.none,
                    // hintStyle: TextStyle(color: Color(0xFF999999)),
                    suffixIcon: Icon(
                      Icons.keyboard_arrow_right_rounded,
                      size: 24,
                      color: ThemeColor.textColorSecond,
                    ),

                    fillColor: const Color(0xffF1F3FB),
                    filled: true,
                    enabledBorder: const OutlineInputBorder(
                      /*边角*/
                      borderRadius: BorderRadius.all(
                        Radius.circular(5), //边角为30
                      ),
                      borderSide: BorderSide(
                        color: Colors.white54, //边线颜色为黄色
                        width: 1, //边线宽度为2
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(5),
                      borderSide: const BorderSide(
                        color: Colors.white54, //边框颜色为绿色
                        width: 1, //宽度为5
                      ),
                    ),
                  ),
                  onTap: () async {
                    DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        minTime: DateTime(1950, 1, 1),
                        maxTime: DateTime(2005, 12, 31),
                        onChanged: (date) {}, onConfirm: (date) {
                      // '$date'

                      _birthdayController.text = date.toString().split(' ')[0];
                    }, currentTime: DateTime.now(), locale: LocaleType.zh);
                  },
                  onChanged: (e) {
                    setState(() {
                      // _loginBtnSelector = _pwdController.text.length >= 6 && e.length >= 11 ? _loginBtnEnable : _loginBtnUnable;
                    });
                  },
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              //地址
              // Container(
              //   alignment: Alignment.topLeft,
              //   margin: const EdgeInsets.only(left: 41),
              //   child: Text("地址", style: TextStyle(fontSize: 16, color: ThemeColor.textColor),),
              // ),
              // Container(
              //   margin: const EdgeInsets.fromLTRB(41, 10, 41, 0),
              //   height: 45,
              //   color: Color(0xFFF6F8FA),
              //
              //   child: TextField(
              //     controller: _addressController,
              //     maxLength: 11,
              //     keyboardType: TextInputType.phone,
              //     cursorColor: const Color(0xFFFB6D99),
              //
              //     style: const TextStyle(
              //         fontSize: 12,
              //         color: Color(0xFF222222)
              //     ),
              //     readOnly: true,
              //     decoration: InputDecoration(
              //       hintText: "请选择",
              //       hintStyle: TextStyle(fontSize: 12, color: ThemeColor.textColorSecond),
              //       counterText: "",
              //       border: InputBorder.none,
              //       // hintStyle: TextStyle(color: Color(0xFF999999)),
              //       suffixIcon: Icon(Icons.keyboard_arrow_right_rounded, size: 24, color: ThemeColor.textColorSecond,),
              //
              //       fillColor: const Color(0xffF1F3FB),
              //       filled: true,
              //       enabledBorder: const OutlineInputBorder(
              //         /*边角*/
              //         borderRadius: BorderRadius.all(
              //           Radius.circular(5), //边角为30
              //         ),
              //         borderSide: BorderSide(
              //           color: Colors.white54, //边线颜色为黄色
              //           width: 1, //边线宽度为2
              //         ),
              //       ),
              //       focusedBorder: OutlineInputBorder(
              //         borderRadius: BorderRadius.circular(5),
              //         borderSide: const BorderSide(
              //           color: Colors.white54, //边框颜色为绿色
              //           width: 1, //宽度为5
              //         ),
              //       ),
              //     ),
              //     onTap:()  {
              //
              //       showPicker(context,_pcaList, (picker, selected) {
              //         final p = _pcaOriginalList[selected[0]]['name'];
              //         final c = _pcaOriginalList[selected[0]]['children'][selected[1]]['name'];
              //         final a = _pcaOriginalList[selected[0]]['children'][selected[1]]['children'][selected[2]]['name'];
              //         setState(() {
              //           _addressController.text = '$p $c $a ';
              //           print('$p $c $a ');
              //           // _user['homeAddr'] = '$p $c $a ';
              //         });
              //       });
              //
              //     },
              //     onChanged: (e) {
              //       setState(() {
              //
              //
              //         // _loginBtnSelector = _pwdController.text.length >= 6 && e.length >= 11 ? _loginBtnEnable : _loginBtnUnable;
              //       });
              //     },
              //   ),
              // ),

              GestureDetector(
                onTap: () {
                  _submit();
                },
                child: Container(
                  height: 45,
                  margin: const EdgeInsets.fromLTRB(41, 50, 41, 0),
                  // margin: const EdgeInsets.symmetric(horizontal: 14),
                  decoration: BoxDecoration(
                      gradient: const LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [Color(0xFFB1A3E4), Color(0xFF7278E5)]),
                      borderRadius: BorderRadius.circular(22.5)),
                  alignment: Alignment.center,
                  child: const Text(
                    "下一步",
                    style: TextStyle(color: Colors.white, fontSize: 18),
                  ),
                ),
              ),
              const SizedBox(
                height: 20,
              )
            ],
          ),
        ),
      ),
    );
  }

  bool _verify(bool sendCode) {
    if (_avatarFilePath.toString().isEmpty) {
      toast("请上传头像");
      return false;
    }

    if (_nickNameController.text.isEmpty) {
      toast("请输入昵称");
      return false;
    }

    if (_birthdayController.text.isEmpty) {
      toast("请选择生日");
      return false;
    }

    // if (_addressController.text.isEmpty) {
    //   toast("请选择地址");
    //   return false;
    // }
    return true;
  }

  _submit() {
    if (!_verify(false)) {
      return;
    }

    loading(() async {
      final res = await Api.getInstance().completeInfoByAppLogin(
        Provider.memberId,
        _nickNameController.text,
        _gender,
        _birthdayController.text,
        _avatarFilePath,
        widget.smsSig,
      );
      if (res['code'] == 0) {
        Navigate.toMain();
        // Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => const AppMain()));
      } else {
        toast(res['msg']);
      }
    });
  }

  void getAlbumImg() {
    if (kIsWeb) {
      loading(() async {
        final uploadInputElement = html.FileUploadInputElement();
        uploadInputElement.multiple = false;
        uploadInputElement.draggable = true;
        uploadInputElement.click();
        uploadInputElement.onChange.listen((event) {
          final file = uploadInputElement.files?.first;

          if (file != null) {
            final uploadInputElement = html.FileUploadInputElement();
            uploadInputElement.multiple = false;
            uploadInputElement.draggable = true;
            uploadInputElement.click();
            uploadInputElement.onChange.listen((event) {
              final file = uploadInputElement.files?.first;
              if (file != null) {
                loading(() async {
                  final formData = html.FormData();
                  formData.appendBlob("avatarfile", file.slice(), file.name);
                  formData.append("memberId", Provider.memberId);
                  Api.getInstance().uploadAvatarFromHtml(formData, (e) {
                    if (e['code'] == 0) {
                      setState(() {
                        _avatarFilePath = e['data']['url'];
                      });
                    } else {
                      ThemeSnackBar.show(context, e['msg']);
                    }
                  });
                });
              }
            });
          }
        });
      });
    } else {
      loading(() async {
        final picker = ImagePicker();

        final pickerFile = await picker.pickImage(
            source: ImageSource.gallery, imageQuality: 50);
        if (pickerFile != null) {
          CroppedFile? croppedImage = await ImageCropper().cropImage(
              sourcePath: pickerFile.path,
              //图片资源
              maxHeight: 500,
              maxWidth: 500,
              aspectRatio: const CropAspectRatio(ratioX: 1, ratioY: 1),
              //裁剪框比例
              uiSettings: [
                AndroidUiSettings(
                    toolbarTitle: '裁剪', lockAspectRatio: true //锁定图片纵横比
                    ),
                IOSUiSettings(
                    title: '裁剪',
                    resetButtonHidden: true,
                    //不显示重置按钮
                    aspectRatioLockEnabled: true,
                    //锁定图片纵横比
                    aspectRatioPickerButtonHidden: true,
                    //隐藏切换纵横比按钮
                    doneButtonTitle: "完成",
                    //confirm按钮文字
                    cancelButtonTitle: "取消" //cancel按钮文字
                    )
              ]); //根据XFile对象的路径获得图片进行裁剪
          //裁剪完成

          if (croppedImage != null) {
            //裁剪后图片的路径
            String filepath = croppedImage.path;
            final res = await Api.getInstance()
                .uploadAvatar(Provider.memberId, filepath); //pickerFile.path
            if (res['code'] == 0) {
              final data = res['data'];
              setState(() {
                _avatarFilePath = data['url'];
                ThemeSnackBar.show(context, res['msg']);
              });
            } else {
              ThemeSnackBar.show(context, res['msg']);
            }
            print("filepath-----$filepath");
          }
        }
        // if (pickerFile != null) {
        //   final res = await Api.getInstance().uploadAvatar(Provider.memberId, pickerFile.path);
        //   if (res?['code'] == 0) {
        //     final data = res['data'];
        //     setState(() {
        //       _avatarFilePath = data['url'];
        //     });
        //
        //   } else {
        //     ThemeSnackBar.show(context, res['msg']);
        //   }
        // }
      });
    }
  }
// _publish() async{
//
//   EasyLoading.show();
//   String urls = "";
//   if (_localFiles.isNotEmpty) {
//     for (var element in _localFiles) {
//       urls += "$element,";
//     }
//   }
//   final res = await Api.getInstance().publishMood(
//       Provider.memberId,
//       urls,
//   );
//   if (res['code'] == 0) {
//     Navigator.pop(context, 0);
//   } else {
//     ThemeSnackBar.show(context, res['msg']);
//   }
//   EasyLoading.dismiss();
// }
}
